package com.zatech.cgnci.project.controller;

import com.zatech.cgnci.project.base.context.UserUtils;
import com.zatech.cgnci.project.base.context.UserVO;
import com.zatech.cgnci.project.base.enums.ResponseCodeEnum;
import com.zatech.cgnci.project.base.exception.GlobalException;
import com.zatech.cgnci.project.base.utils.ConvertUtils;
import com.zatech.cgnci.project.base.utils.VerifyUtils;
import com.zatech.cgnci.project.dto.CgnciLoginDTO;
import com.zatech.cgnci.project.entity.CgnciUserInfoDO;
import com.zatech.cgnci.project.entity.UserEntity;
import com.zatech.cgnci.project.service.CgnciUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author user
 */
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Api(produces = "application/json", tags = "登录api接口文档")
public class CgnciLoginController {

    private final CgnciUserInfoService cgnciUserInfoService;


    @ApiOperation(value = "姓名-工号登录")
    @PostMapping("/login")
    public UserVO login(@RequestBody @Valid CgnciLoginDTO loginDTO) {
        List<UserEntity> result = new ArrayList<>();
        // 查询用户
        List<CgnciUserInfoDO> userList = cgnciUserInfoService.list();
        result.addAll(ConvertUtils.convert(userList, UserEntity.class));
        result.addAll(UserEntity.USER_ENTITY_LIST);
        UserEntity userEntity = result.stream().filter(userToken -> loginDTO.getUsercode().equals(userToken.getUsercode()) && loginDTO.getUsername().equals(userToken.getUsername())).findFirst().orElse(null);
        if (VerifyUtils.isEmpty(userEntity)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "姓名-工号错误");
        }
        // 生成token
        String token = UUID.randomUUID().toString().replace("-", "");
        // 存入map
        UserEntity.USER_ENTITY_MAP.put(token, userEntity);
        //UserContext.setUser(userEntity);
        return UserVO.builder().token(token).userEntity(userEntity).build();
    }


    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/getUserInfo")
    public UserEntity getUserInfo() {
        return UserUtils.getCurrentUserInfo();
    }

    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public void logout() {
        UserUtils.currentUserLogout();
    }

    @ApiOperation(value = "获取所有用户信息")
    @GetMapping("/listUserInfo")
    public List<UserEntity> listUserInfo() {
        List<UserEntity> result = new ArrayList<>();
        // 查询用户
        List<CgnciUserInfoDO> userList = cgnciUserInfoService.list();
        result.addAll(ConvertUtils.convert(userList, UserEntity.class));
        result.addAll(UserEntity.USER_ENTITY_LIST);
        return result;
    }


}
